package agency.tango.materialintro;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSliderProvider;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

public class ComponentDemoAdapter extends PageSliderProvider {
    private Context context;
    private List<DemoView> views;

    public ComponentDemoAdapter(Context context) {
        this.context = context;
        this.views = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return this.views == null ? 0 : this.views.size();
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int position) {
        DemoView view;
        ComponentContainer.LayoutConfig config = new ComponentContainer.LayoutConfig
                (ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        if (this.views != null && this.views.size() > position) {
            view = this.views.get(position);
            if (view != null && view.getRootView() != null) {
                componentContainer.addComponent(view.getRootView(), config);
                views.set(position, view);
                return view.getRootView();
            }
        }
        view = this.getItem(position);
        while (this.views.size() <= position) {
            this.views.add(null);
        }
        this.views.set(position, view);
        if (view == null && view.getRootView() != null) {
            componentContainer.addComponent(view.getRootView(), config);
            return view.getRootView();
        } else {
            return new Component(componentContainer.getContext());
        }

    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int position, Object obj) {
        if (obj instanceof Component && componentContainer != null) {
            componentContainer.removeComponent((Component) obj);
        }
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return component == o;
    }

    public DemoView getItem(int position) {
        if (this.views == null || position < 0 || position >= views.size() || views.get(position) == null) {
            return null;
        }
        return views.get(position);
    }

    public void addItem(DemoView view) {
        if (this.views == null || view == null) {
            return;
        }
        views.add(getCount(), view);
        notifyDataChanged();
    }
}
